package com.matrix.app.flux.aichat.controller;

import com.matrix.app.flux.aichat.data.AiChatRequestDto;
import com.matrix.app.flux.aichat.data.AiChatResponseVo;
import com.matrix.app.flux.aichat.service.AiChatService;
import com.matrix.framework.core.common.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * AI聊天控制器
 *
 * Copyright © 海平面工作室 版权所有
 *
 * @Author: Leo
 * @Create: 2024-01-22 10:00:00
 * @Since 1.2
 */
@RestController
@RequestMapping("/ai/chat")
public class AiChatController {

    @Autowired
    private AiChatService aiChatService;

    /**
     * 发送聊天消息
     *
     * @param request 聊天请求
     * @return 聊天响应
     */
    @PostMapping("/send")
    public Mono<Result<AiChatResponseVo>> sendMessage(@RequestBody AiChatRequestDto request) {
        return aiChatService.chat(request)
                .map(Result::ok)
                .onErrorResume(e -> Mono.just(Result.<AiChatResponseVo>fail().message(e.getMessage())));
    }

    /**
     * 流式聊天
     *
     * @param request 聊天请求
     * @return 流式响应
     */
    @PostMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> streamChat(@RequestBody AiChatRequestDto request) {
        return aiChatService.streamChat(request)
                .onErrorResume(e -> Flux.just("data: {\"error\":\"" + e.getMessage() + "\"}\n\n"));
    }

    /**
     * 健康检查
     *
     * @return 健康状态
     */
    @GetMapping("/health")
    public Mono<Result<String>> healthCheck() {
        return Mono.just(Result.ok("AI Chat Service is running"))
                .onErrorResume(e -> Mono.just(Result.<String>fail().message("Service unavailable")));
    }
}